<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
[#include "/includes/header.html" /]
<link rel="stylesheet" type="text/css" href="${webctx}/resources/css/jquery.filer.css"/>
<link rel="stylesheet" type="text/css" href="${webctx}/resources/css/jquery.filer-dragdropbox-theme.css"/>
<link rel="stylesheet" type="text/css" href="${webctx}/resources/css/product.css"/>
<script src="${webctx}/resources/js/jquery.filer.min.js"></script>
<script src="${webctx}/resources/js/product/product.add.js"></script>
<script type="text/javascript" charset="utf-8" src="${webctx}/resources/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="${webctx}/resources/ueditor/ueditor.all.min.js"></script>
<script type="text/javascript">
var isShowStep1="0";
var isShowStep2="0";		
function addPicture(obj){
	var params={};
	params.model=obj;
	obz.selectImage(params, function (ImgPath, ImgUrl) {
		 var newlistImg=ImgPath.split(",");
		 var newlistImgUrl=ImgUrl.split(",");
		 for (var i = 0; i < newlistImg.length; i++) {
			 if(obj){
				 var reValue=$(".js-picture-listss li").find("input[name='image']").val();
				  if (typeof(reValue)== "undefined"){
					  $(".js-picture-listss").append('<li class="sort"><img src="'+newlistImg[i]+'" id="imgId"  class="js-img-preview">'
								 +'<input name="image" value="'+newlistImgUrl[i]+'" type="hidden"  class="js-img-preview">'
								 +'<a class="js-delete-picture close-modal small hide" onclick="deleteImg(this);">×</a></li>');
				 }else{
					  $("#imgId").attr('src',newlistImg[i]);
					  $(".js-picture-listss li").find("input[name='image']").val(newlistImgUrl[i]);
				  } 				 
			  }else{
				 $(".js-picture-lists").append('<li class="sort"><img src="'+newlistImg[i]+'"  class="js-img-preview">'
					 +'<input name="imgList" value="'+newlistImgUrl[i]+'" type="hidden"  class="js-img-preview">'
					 +'<a class="js-delete-picture close-modal small hide" onclick="deleteImg(this);">×</a></li>');
		          } 
		 }
		 $(".col-md-5 ul>li").hover(function(){
				$(this).find("a").removeClass("hide");
			   $(this).find("a").addClass("hover");
			},function(){
				 $(this).find("a").addClass("hide");  
				 $(this).find("a").removeClass("hover");
			});
	});
}
function nextStepTwo1(){
	if(catagory == ''){
		$("#assign_error_msg").html("必须选择一个商品类目。");
		isShowStep1="0";
		return false;
	}else{
		isShowStep1="1";
	}
}

function nextStepTwo(){
	if(catagory == ''){
		$("#assign_error_msg").html("必须选择一个商品类目。");
		isShowStep1="0";
		return false;
	}else{
		isShowStep1="1";
	}
	$('#myTab a[href="#js-step-2"]').tab('show')
}

function nextStepThree(){
	clearError();
	var type = $("input[name='is_unified_spec']:checked").val();
	var hasErr = false;
	var hasError = false;
	var params = {}, error = {};
	var productName = $("#product_name").val();
	if($.trim(productName) =="") {error.error_product_name = "商品名不能为空"; } else {error.error_product_name=""; params.product_name = $.trim(productName);}
	if(type == "true"){		
		var productPrice = $("#product_price").val();
		if($.trim(productPrice) =="") {error.error_product_price = "商品价格不能为空"; } else {error.error_product_price =""; params.product_price = $.trim(productPrice);}	
	}
	
	for(var key in error){
		if(error[key]!=""){
			//alert(key);
			if(!hasError) hasError = true;
			$("#"+key).addClass("has-error");
			$("#"+key).find("label").text(error[key]);
		}else{
			$("#"+key).removeClass("has-error");
			$("#"+key).find("label").empty();
		}
	}
	if($(".js-picture-lists li").length<=1){
		if(!hasErr) hasErr=true;
		$("#image_error_msg").html("商品图至少有一张。");
		//return;
	}
	if($(".js-picture-listss li").length<=1){
		if(!hasErr) hasErr=true;
		$("#only_error_msg").html("商品展示图至少有一张。");
		//return;
	}
	if($(".js-picture-listss li").length>2){
		if(!hasErr) hasErr=true;
		$("#only_error_msg").html("商品展示图只能有一张。");
		//return;
	}
	
	if($("#specificationSelect input[type=checkbox]:checked").length>=1){
		if($("ul.Item" + " input[type=checkbox]:checked").length<=0){
			if(!hasErr) hasErr=true;
			$("#specificationValue_error_msg").html("商品规格值至少有一个。");
		}
	}
	 
	if($("#bodyss tr").length>=1){
 	$("#bodyss tr").each(function(i,obj){
 		var price_input = $(obj).find("input[name='price_s']");
 		if(price_input.val()==""){	
 			if(!hasErr) hasErr=true;
 			price_input.css("border-color", "#ff5454");
 			$(obj).find(".price_error_msg").html("价格不能为空");
			//return ;
		}
 		var stock_input = $(obj).find("input[name='stock_s']");		
 		if(stock_input.val()==""){
 			if(!hasErr) hasErr=true;
 			stock_input.css("border-color", "#ff5454");
 			$(obj).find(".stock_error_msg").html("库存不能为空");
			//return ;
		}
 				
	}); 
	}
	
	var p1=$('#delivery_memo').children('option:selected').val();
	var type = $("input[name='is_unified_spec']:checked").val();
	var valuation_value="0";
	 $.post(obz.ctx+"/delivery/getDeliveryMemoName", {id:p1}, function(json) {
		 var dataList = json;
			if(dataList.length>0){
				var valuation_type=dataList[0].valuation_type;
				if(valuation_type=="2"&&type=="false"){
					if($("#bodyWeight tr").length>=1){
					 	$("#bodyWeight tr").each(function(i,obj){
					 		var weight_input = $(obj).find("input[name='weight_s']");
					 		if(weight_input.val()==""){	
					 			valuation_value="1";
					 			weight_input.css("border-color", "#ff5454");
					 			$(obj).find(".weight_error_msg").html("重量不能为空");
							}
					 			
						}); 
						}
				}else if(valuation_type=="2"&&type=="true"){
					var delivery_weight=$("input[name='delivery_weight']");
					if(delivery_weight.val()==""){
						valuation_value="1";
					  delivery_weight.css("border-color", "#ff5454");
					  $(".delivery_weight_error_msg").html("物流重量不能为空");

					}
				}	
			}	
	 });
	
	var delivery_type=$("input[name='delivery_type']:checked").val();
		
	if(delivery_type=="0"){
		var delivery_fees=$("input[name='delivery_fees']");
		if(delivery_fees.val()==""){
		  if(!hasErr) hasErr=true;
		  delivery_fees.css("border-color", "#ff5454");
		  $(".delivery_fees_error_msg").html("邮费不能为空");
		}
	}else{
		
		var delivery_memo=$("#delivery_memo option:selected").val();
		if(delivery_memo==""||delivery_memo=="0"){
			if(!hasErr) hasErr=true;
			$(".delivery_template_error_msg").html("请选择运费模版");
		}
		
	}
	
	if(hasErr){
		isShowStep2="0";
		return false;
	}else{
		isShowStep2="1";
	}
	
	if(hasError){
		isShowStep2="0";
		return false;
	}else{
		isShowStep2="1";
	}
	$('#myTab a[href="#js-step-3"]').tab('show')
}
function lastStepTwo(){
	$('#myTab a[href="#js-step-2"]').tab('show')
}
function lastStepFirst(){
	$('#myTab a[href="#js-step-1"]').tab('show')
}
var listImg="";
var listImgUrl="";
var listUpload="";
var catagory="";
var selectImg = new Array();
$(document).ready(function() {
	
	$('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
          nextStepTwo1();
            if(isShowStep1=="1"){
            	$(e).tab('show')
            }else{
            	$(e).tab('hide')
            }
           
        });
	
	
	$(".widget-goods-klass .widget-goods-klass-item").click(function(){
		catagory=""
		$("#productCategoryName").val();
		$(".widget-goods-klass .widget-goods-klass-item").each(function(){
			$(this).removeClass("current");
		});
		$(this).addClass("current");
		//alert($(this).attr("category-id"));
		//alert($(this).attr("category-name"));
		
		catagory=$(this).attr("category-id");
		$("#productCategoryId").val(catagory);
		$("#productCategoryName").html($(this).attr("category-name"));
		$("#assign_error_msg").html("");
		return false;
	});
	
	
	$('#img_list_dialog').on('hidden.bs.modal', function () {
		selectImg.length=0;
		listImg="";
		$("ul.selectMonth li").each(function(){					    	
	    	$(this).removeClass("active");
	    });
		$("#saveImg").addClass("disabled");
		$(".selected-count-region").addClass("hidden");
		// return false;
	});

	$('#img_upload_dialog').on('hidden.bs.modal', function () {
		$(".js-picture-list").empty();
		 return false;
	});
	
	$(".add-local-image-button").click(function(){
		 $("#img_list_dialog").modal("hide");
		 $("#img_upload_dialog").modal("show");
	}); 
});

function prices(){
	$("#js-price").show();
	$(".js-batch-type").hide();
}

function stocks(){
	$("#js-stock").show();
	$("#js-price").hide();
	$(".js-batch-type").hide();
}
function cancel(){
	$(".js-batch-type").show();
	$("#js-price").hide();
	$("#js-stock").hide();
}

function pricesSave(){
	
	var priceId=$("#priceId").val();
	 if(priceId !=''){
		// alert(priceId);
		 $("input[name='price_s']").empty();
		 $("input[name='price_s']").val(priceId);
	$(".js-batch-type").show();
	$("#js-price").hide();
	$("#js-stock").hide();
	 }else{
		 //$.message("warn", "请输入价格值！");
		 alert("请输入价格值！");
	    	return false; 
	 }
}

function stocksSave(){
	var stockId=$("#stockId").val();
    if(stockId !=''){
    	
    $("input[name='stock_s']").empty();
    $("input[name='stock_s']").val(stockId);	
	$(".js-batch-type").show();
	$("#js-price").hide();
	$("#js-stock").hide();
    }else{
    	//$.message("warn", "请输入库存值！");
    	alert("请输入库存值！");
    	return false;
    }
}

function checkNum(obj) {  
    if (isNaN(obj.value)) {  
        obj.value = "";  
    }  
    if (obj != null) {  
        if (obj.value.toString().split(".").length > 1 && obj.value.toString().split(".")[1].length > 2) {  
            obj.value = "";  
        }  
    }  
} 
var step ="";
var items = new Array();
var params = {};
var itemsAll = new Array();
function saveTask(){
	 var trList = $("#bodyss").children("tr");
	 var trListWeight = $("#bodyWeight").children("tr");
	 $.each(items, function (index, item) {
		 var tdArr = trList.eq(index).find("td");
		 var tdArrWeight = trListWeight.eq(index).find("td");
		 var price = tdArr.eq(tdArr.length-2).find("input").val();//价格
	     var stock = tdArr.eq(tdArr.length-1).find("input").val();//库存
	     var weight= tdArrWeight.eq(tdArrWeight.length-1).find("input").val();//重量
		 var entity = new Object();
		    entity.specificationValue=item;
			entity.price = price;
			entity.stock = stock;
			entity.weight= weight;
			itemsAll.push(entity);	 
	 }); 		 
	 params.items =  JSON.stringify(itemsAll);
$("#allStocks").val(params.items);
}
$(function (){

	 $("#specificationSelect :checkbox").click(function(){		
	     var code_Values =$("#specificationSelect input[type=checkbox]:checked");      
			if(code_Values.length<=3){
			var $this = $(this);
			if ($this.prop("checked")) {
				$("#specificationProductTable").find("tr.specification_" + $this.val()).removeClass("hidden");
				$("#Title_"+$this.val()).addClass("Father_Title");
			} else {
				$("#specificationProductTable").find("tr.specification_" + $this.val()).addClass("hidden");
			 	$("#Item_"+$this.val() +" li").find("label").find("input[type=checkbox]").each(function(i,n){
			 	   $(n).prop('checked',false);
				});	   
			 	if(code_Values.length==0){
			 		step.Creat_Table();	
			 		$("#Title_"+$this.val()).removeClass();
					
			 	}else{
				$("#Title_"+$this.val()).removeClass();
				step.Creat_Table();	
			 	}
			}	
			}else{
				//$.message("warn", "只能选择三个规格");
				alert("只能选择三个规格！");
				$(this).prop('checked',false);
				return false;
			}	
		});
	 
	 
	 $("#specificationProductTable label").bind("change", function () {
	        step.Creat_Table();
	    });
	    var step = {
	        Creat_Table: function () {
	            step.hebingFunction();
	            var SKUObj = $(".Father_Title");
	            //var skuCount = SKUObj.length;//
	            var arrayTile = new Array();//标题组数
	            var arrayInfor = new Array();//盛放每组选中的CheckBox值的对象
	            var arrayInforId = new Array();//盛放每组选中的CheckBox id值的对象
	            var arrayColumn = new Array();//指定列，用来合并哪些列
	            var bCheck = true;//是否全选
	            var columnIndex = 0;
	            var s="";
	            $.each(SKUObj, function (i, item){
	            	 arrayColumn.push(columnIndex);
	                 columnIndex++;
	                 arrayTile.push(SKUObj.find("li").eq(i).html().replace("：", ""));
	            	s+=$(item).attr("id")+",";
	            });
	            var newstr=s.substring(0,s.length-1);
	            var td_array = newstr.split(",");
	            
	            $.each(td_array, function (i, values) {
	            	
	            	 var itemName =values;
	                 //选中的CHeckBox取值
	                 var order = new Array();
	                 var orderId = new Array();
	                 $("." + itemName + " input[type=checkbox]:checked").each(function (){
	                 /* 	var orderObj = new Object();
	                 	orderObj.id = $(this).val();
	                 	Father_Item
	                 	
	                 	 $("." + itemName + " input[type=checkbox]:checked").each(function (){
	                 	orderObj.vaule = $(this).attr("data-val");  */
	                     order.push($(this).attr("data-val"));
	                     orderId.push($(this).attr("data-value"));
	                 	//order.push(orderObj);
	                 });
	                 arrayInforId.push(orderId);
	                 arrayInfor.push(order);
	                 if (order.join() == ""){
	                     bCheck = false;
	                 }
	            	//alert(values);
	            });
	            
	            if (arrayInfor.length <=0){
	                bCheck = false;
	            }
	            //开始创建Table表
	            if (bCheck == true) {
	            	
	            	var RowsCount = 0;
	            	//创建重量表
	                $("#createdWeight").html("");
	                var tableWeight = $("<table id=\"weightTable\" class=\"table table-striped table-bordered\"></table>");
	                tableWeight.appendTo($("#createdWeight"));
	                var theadWeight = $("<thead align=\"left\"></thead>");
	                theadWeight.appendTo(tableWeight);
	                var trHeadWeight = $("<tr></tr>");
	                trHeadWeight.appendTo(theadWeight);
	              //创建表头
	                $.each(arrayTile, function (index, item) {
	                    var tdWeight = $("<th>" + item + "</th>");
	                    tdWeight.appendTo(trHeadWeight);
	                });
	                var itemColumHeadWeight = $("<th  style=\"width:30%;\">重量(Kg)</th> ");
	                itemColumHeadWeight.appendTo(trHeadWeight);
	                var tbodyWeight = $("<tbody id=\"bodyWeight\"></tbody>");
	                tbodyWeight.appendTo(tableWeight);
                    //创建规格表
	                $("#createTable").html("");
	                var table = $("<table id=\"process\" class=\"table table-striped table-bordered\"></table>");
	                table.appendTo($("#createTable"));
	                var thead = $("<thead align=\"left\"></thead>");
	                thead.appendTo(table);
	                var trHead = $("<tr></tr>");
	                trHead.appendTo(thead);
	                //创建表头
	                $.each(arrayTile, function (index, item) {
	                    var td = $("<th>" + item + "</th>");
	                    td.appendTo(trHead);
	                });
	                var itemColumHead = $("<th  style=\"width:70px;\">价格（￥）</th><th style=\"width:70px;\">库存</th> ");
	                itemColumHead.appendTo(trHead);
	                var tbody = $("<tbody id=\"bodyss\"></tbody>");
	                var tfoot=$("<tfoot></tfoot>");
	                var tfootColum=$("<div class=\"batch-opts\"> 批量设置：<span class=\"js-batch-type\" style=\"display: inline;\">"
	                         +"<a id=\"js-batch-price\" href=\"javascript:;\" onclick=\"prices();\">价格</a>&nbsp;&nbsp;<a class=\"js-batch-stock\" href=\"javascript:;\" onclick=\"stocks();\">库存</a></span>"
	                        +"<span id=\"js-stock\" class=\"js-batch-form\" style=\"display: none;\">"
	                        +"<input class=\"js-batch-txt\"  id=\"stockId\" placeholder=\"请输入库存\" maxlength=\"9\" type=\"text\" onkeyup=\"checkNum(this)\">"
	                        +"<a class=\"js-batch-save\" href=\"javascript:;\" onclick=\"stocksSave();\">保存</a>"
	                        +"<a class=\"js-batch-cancel\" href=\"javascript:;\" onclick=\"cancel();\">取消</a>"
	                        +"<p class=\"help-desc\"></p></span>"
	                        +"<span id=\"js-price\" class=\"js-batch-form\" style=\"display: none;\">"
	                        +"<input class=\"js-batch-txt\" id=\"priceId\" placeholder=\"请输入价格\" maxlength=\"9\" type=\"text\" onkeyup=\"checkNum(this)\">"
	                        +"<a class=\"js-batch-save\" href=\"javascript:;\" onclick=\"pricesSave();\">保存</a>"
	                        +"<a class=\"js-batch-cancel\" href=\"javascript:;\" onclick=\"cancel();\">取消</a>"
	                        +"<p class=\"help-desc\"></p></span>"
	                        +"</div>");
	/*                         +"<tr> <th><span class=\"requiredField\">*</span>总库存:</th>"
	                        +"  <td><input type=\"text\" id=\"allStock\" name=\"stock\" class=\"text\" maxlength=\"9\"  disabled=\"disabled\"/></td>"
	                        +"</tr>" */
	                tfootColum.appendTo(tfoot);
	                tfoot.appendTo(table);
	                tbody.appendTo(table);
	               
	                ////生成组合
	                var zuheId=step.doExchange(arrayInforId);
	                if (zuheId.length > 0) {
	                	items.length=0;
		                $.each(zuheId, function (index, item) {
		                    items.push(item);
		                });
	                }
	                
	                var zuheDate = step.doExchange(arrayInfor);
	                //物流重量
	                if (zuheDate.length > 0) {
	                    //创建行
	                    $.each(zuheDate, function (index, item) {
	                        var td_array = item.split(",");
	                        var trWeight = $("<tr></tr>");
	                        trWeight.appendTo(tbodyWeight);
	                        $.each(td_array, function (i, values) {
	                            var tdWeight = $("<td>" + values + "</td>");
	                            tdWeight.appendTo(trWeight);
	                        });
	                        var td1 = $("<td class=\"col-md-2\"><span class=\"requiredField\"></span><input name=\"weight_s\" class=\"weights form-control\" type=\"text\" value=\"\" onkeyup=\"checkNum(this)\"><label class=\"weight_error_msg\" style=\"color:red;\"></label></td>");
	                        td1.appendTo(trWeight);
	                    });
	                }
	                //规格
	                if (zuheDate.length > 0) {
	                    //创建行
	                    $.each(zuheDate, function (index, item) {
	                        var td_array = item.split(",");
	                        var tr = $("<tr></tr>");
	                        tr.appendTo(tbody);
	                        $.each(td_array, function (i, values) {
	                            var td = $("<td>" + values + "</td>");
	                            td.appendTo(tr);
	                        });
	                        var td1 = $("<td class=\"col-md-2\"><span class=\"requiredField\"></span><input name=\"price_s\" class=\"price form-control\" type=\"text\" value=\"\" onkeyup=\"checkNum(this)\"><label class=\"price_error_msg\" style=\"color:red;\"></label></td>");
	                        td1.appendTo(tr);
	                        var td2 = $("<td class=\"col-md-2\"><span class=\"requiredField\"></span><input name=\"stock_s\" class=\"stocks form-control\" type=\"text\" value=\"\" onkeyup=\"checkNum(this)\"><label class=\"stock_error_msg\" style=\"color:red;\"></label></td>");
	                        td2.appendTo(tr);
	                    });
	                }
	                //结束创建Table表
	                arrayColumn.pop();//删除数组中最后一项
	                //合并单元格
	                $(table).mergeCell({
	                    // 目前只有cols这么一个配置项, 用数组表示列的索引,从0开始
	                    cols: arrayColumn
	                });
	            } else{
	                //未全选中,清除表格
	                document.getElementById('createTable').innerHTML="";
	                document.getElementById('createdWeight').innerHTML="";
	            }
	        },//合并行
	        hebingFunction: function () {
	            $.fn.mergeCell = function (options) {
	                return this.each(function () {
	                    var cols = options.cols;
	                    for (var i = cols.length - 1; cols[i] != undefined; i--) {
	                        // fixbug console调试
	                        // console.debug(cols[i]);
	                        mergeCell($(this), cols[i]);
	                    }
	                    dispose($(this));
	                });
	            };
	            function mergeCell($table, colIndex) {
	                $table.data('col-content', ''); // 存放单元格内容
	                $table.data('col-rowspan', 1); // 存放计算的rowspan值 默认为1
	                $table.data('col-td', $()); // 存放发现的第一个与前一行比较结果不同td(jQuery封装过的), 默认一个"空"的jquery对象
	                $table.data('trNum', $('tbody tr', $table).length); // 要处理表格的总行数, 用于最后一行做特殊处理时进行判断之用
	                // 进行"扫面"处理 关键是定位col-td, 和其对应的rowspan
	                $('tbody tr', $table).each(function (index) {
	                    // td:eq中的colIndex即列索引
	                    var $td = $('td:eq(' + colIndex + ')', this);
	                    // 取出单元格的当前内容
	                    var currentContent = $td.html();
	                    // 第一次时走此分支
	                    if ($table.data('col-content') == '') {
	                        $table.data('col-content', currentContent);
	                        $table.data('col-td', $td);
	                    } else {
	                        // 上一行与当前行内容相同
	                        if ($table.data('col-content') == currentContent) {
	                            // 上一行与当前行内容相同则col-rowspan累加, 保存新值
	                            var rowspan = $table.data('col-rowspan') + 1;
	                            $table.data('col-rowspan', rowspan);
	                            // 值得注意的是 如果用了$td.remove()就会对其他列的处理造成影响
	                            $td.hide();
	                            // 最后一行的情况比较特殊一点
	                            // 比如最后2行 td中的内容是一样的, 那么到最后一行就应该把此时的col-td里保存的td设置rowspan
	                            if (++index == $table.data('trNum'))
	                                $table.data('col-td').attr('rowspan', $table.data('col-rowspan'));
	                        } else { // 上一行与当前行内容不同
	                            // col-rowspan默认为1, 如果统计出的col-rowspan没有变化, 不处理
	                            if ($table.data('col-rowspan') != 1) {
	                                $table.data('col-td').attr('rowspan', $table.data('col-rowspan'));
	                            }
	                            // 保存第一次出现不同内容的td, 和其内容, 重置col-rowspan
	                            $table.data('col-td', $td);
	                            $table.data('col-content', $td.html());
	                            $table.data('col-rowspan', 1);
	                        }
	                    }
	                });
	            }
	            // 同样是个private函数 清理内存之用
	            function dispose($table) {
	                $table.removeData();
	            }
	        },
	        //组合数组
	        doExchange: function (doubleArrays) {
	            var len = doubleArrays.length;
	            if (len >= 2) {
	                var arr1 = doubleArrays[0];
	                var arr2 = doubleArrays[1];
	                var len1 = doubleArrays[0].length;
	                var len2 = doubleArrays[1].length;
	                var newlen = len1 * len2;
	                var temp = new Array(newlen);
	                var index = 0;
	                for (var i = 0; i < len1; i++) {
	                    for (var j = 0; j < len2; j++) {
	                        temp[index] = arr1[i] + "," + arr2[j];
	                        index++;
	                    }
	                }
	                var newArray = new Array(len - 1);
	                newArray[0] = temp;
	                if (len > 2) {
	                    var _count = 1;
	                    for (var i = 2; i < len; i++) {
	                        newArray[_count] = doubleArrays[i];
	                        _count++;
	                    }
	                }
	                //console.log(newArray);
	                return step.doExchange(newArray);
	            }
	            else {
	                return doubleArrays[0];
	            }
	        }
	    }
	    return step;
	 
});
function deleteImg(obj){
	$(obj).parent().remove();
}

function clearError(){
	$("#image_error_msg,.price_error_msg,#only_error_msg,#specificationValue_error_msg,.stock_error_msg,.weight_error_msg,#assign_error_msg,.delivery_template_error_msg,.delivery_fees_error_msg,.delivery_weight_error_msg").empty();
	$("#bodyss tr").each(function(i,obj){
		$(obj).find("input[name='price_s']").css("border-color", "");
		$(obj).find("input[name='stock_s']").css("border-color", "");
	});
	$("#bodyWeight tr").each(function(i,obj){
		$(obj).find("input[name='weight_s']").css("border-color", "");
	});
	var delivery_fees=$("input[name='delivery_fees']");
	  delivery_fees.css("border-color", "");
	var delivery_weight=$("input[name='delivery_weight']");
	  delivery_weight.css("border-color", "");
}

function changeType(){
	var type = $("input[name='is_unified_spec']:checked").val();
	if(type=="true"){
		$("#unified").show();
		$("#allSpec").hide();
		}else{
	    $("#unified").hide();
	    $("#allSpec").show();
		}
	
	if(type=="true"){
		$("#unified_weight").show();
		$("#disunified_weight").hide();
		}else{
	    $("#unified_weight").hide();
	    $("#disunified_weight").show();
		}
	}

function saveTaskForm(){
	saveTask();
	clearError();
	$("#inputForm").submit();
}
</script>
</head>
<body class="fixed-sidebar full-height-layout gray-bg">
[@layout]
<form id="inputForm" action="${webctx}/product/save" method="post">
<div class="wrapper wrapper-content">
	<div class="row content-tabs">
		<nav class="page-tabs J_menuTabs">
	       <div class="page-tabs-content" style="margin-left: 0px;">
	           <a href="${webctx}/product" class="J_menuTab active">商品</a>
		       <a href="${webctx}/category" class="J_menuTab">分类 </a>
		       <a href="${webctx}/specification" class="J_menuTab">规格 </a>
		       <a href="${webctx}/delivery" class="J_menuTab">运费模板</a>
	       </div>
	   	</nav>
	</div>
	<div class="ibox-title row">
		<h2><small><a href="${webctx}/product">《返回列表</a></small></h2>
	</div>
	<div class="tabs-container row" style="padding-top: 12px;">
        <ul class="nav nav-tabs" id="myTab">
            <li class="active"><a role="tab" data-toggle="tab" href="#js-step-1">1.选择分类</a></li>
            <li><a role="tab" data-toggle="tab" href="#js-step-2">2.基本信息</a></li>
            <li><a role="tab" data-toggle="tab" href="#js-step-3">3.商品详情</a></li>
        </ul>
    </div>
	<div class="tab-content ibox-content row col-sm-9">
    <div id="js-step-1"  role="tabpanel" class="tab-pane active">
      <div class="form-horizontal fm-goods-info">
          <div id="class-info-region" class="goods-info-group">
	        <div class="js-goods-klass">
	           <div class="class-block">
	                <div class="js-class-block control-group">
	                  <div class="controls">
			            <div class="widget-goods-klass">
			            
			            [#list productCategory as productCategory]
			            <div class="widget-goods-klass-item" category-id="${productCategory.id}" category-name="${productCategory.name}">
				                <span class="widget-goods-klass-name"> ${productCategory.name}  </span>    
				            </div>
			            [/#list]
				            <div class="widget-goods-klass-item" category-id="8" category-name="其他">
				                <span class="widget-goods-klass-name">其他 </span>  
				                <ul class="widget-goods-klass-children" style="display: none;">
                            <li data-id="8-1">
                                <label class="checkbox-inline"><input name="goods-class-2" class="frm_radio" type="radio"/>礼品鲜花
                                </label>
                            </li>
                            <li data-id="8-2">
                                <label class="checkbox-inline"><input name="goods-class-2" class="frm_radio" type="radio"/>餐饮外卖
                                </label>
                            </li>
                            <li data-id="8-3">
                                <label class="checkbox-inline"><input name="goods-class-2" class="frm_radio"  type="radio"/>丽人健身
                                </label>
                            </li>
                            <li data-id="8-4">
                                <label class="checkbox-inline"><input name="goods-class-2" class="frm_radio" type="radio"/>休闲娱乐
                                </label>
                            </li>
                            <li data-id="8-5">
                                <label class="checkbox-inline"><input type="radio" class="frm_radio" name="goods-class-2" />酒店客栈
                                </label>
                            </li>
                             <li data-id="8-1">
                                <label class="checkbox-inline"><input name="goods-class-2" class="frm_radio"  type="radio"/>礼品鲜花
                                </label>
                            </li>
                          </ul>  
				            </div>
				            <label id="assign_error_msg" style="color:red;"></label>
		                </div>
		               </div>
	                </div>
                </div>
	        </div>
      </div>
    </div>
    
    <div class="panel-heading" style="background-color:#f8f8f8;border-bottom:5px solid #fff;height: 50px;text-align: center;">
      <button type="button"  onclick="nextStepTwo();" class="btn  btn-primary">下一步</button>
   </div>
    
	</div>
	<div id="js-step-2"  role="tabpanel" class="tab-pane">
	   <div class="form-horizontal fm-goods-info">
	     <div id="base-info-region" class="goods-info-group">
	         <div class="goods-info-group-inner">
	             <div class="info-group-title vbox">
					<div class="group-inner">基本信息</div>
				 </div>
				 <div class="info-group-cont vbox">
                       <div class="group-inner">
                          <div class="form-group">
                             <label class="col-md-2 control-label">商品类目：</label>
                             <div class="col-md-5">
                           <div class="static-value" style="font-size: 14px;vertical-align: middle;line-height: 30px;"><span id="productCategoryName"></span></div>
                           <input type="hidden" id="productCategoryId" name="productCategoryId"/>
                             </div>
                          </div>
                          <div class="form-group">
                             <label class="col-md-2 control-label">商品展示图：<span style="color: red;"><em>*</em></span></label>
                             
                             <div class="col-md-5">
                                 <ul class="js-picture-listss app-image-list">
					                <li><a href="javascript:;" onclick="addPicture(true);" class="add-goods js-add-picture show">+加图</a></li>
				                 </ul>
				                 <label id="only_error_msg" style="color:red;"></label>
					          </div>
                          </div>
                       </div>
                 </div>
	         </div>
	         <div class="goods-info-group-inner">
	             <div class="info-group-title vbox">
					<div class="group-inner">库存/规格</div>
				<input type="hidden" id="allStocks"  name="stocks" value="" class="form-control" />
				 </div>
				 <div class="info-group-cont vbox">
                        <div class="group-inner">
                           <div class="form-group">
					            <label class="col-md-2 control-label">规格设置</label>
					            <div class="col-md-8">
					                <div class="sign_list">
                         	        <label class="radio-inline" for="inline-radio1">
                                     <input id="checkbox4" name="is_unified_spec" class="frm_radio" value="true" onclick="changeType();" checked="checked" type="radio"/>
                                      <span>统一规格</span>
                         	        </label>
                         	        
                         	         <label class="radio-inline" for="inline-radio1">
                                     <input id="checkbox4" name="is_unified_spec" class="frm_radio" value="false" onclick="changeType();" type="radio"/>
                                      <span>多规格</span>
                         	        </label>
                         	        </div>
                         	     </div>
                         	 </div>
                          <div class="form-group" id="allSpec" style="display: none;">
                             <label class="col-md-2 control-label">商品规格：<span style="color: red;"><em>*</em></span></label>
                             <div class="col-md-10">
                             <table class="table table-striped">
                              <tr>
                              <td>选择规格项目</td>
				                 <td>
					               <div id="specificationSelect" class="specificationSelect">
										<ul>
										[#list specificationResultDto as ResultDto]
                                           [#list ResultDto.specification as specification]
												<li>
													<label>
														<input type="checkbox" name="specificationIds" value="${specification.id}" />${specification.name}
														[#if specification.memo??]
															<span class="gray">[${specification.memo}]</span>
														[/#if]
													</label>
												</li>
											[/#list]
										[/#list]
										</ul>
					               </div>
					               </td>
					               </tr>
					               <tr>
					               <td>选择规格值
					               <label id="specificationValue_error_msg" style="color:red;"></label>
					               </td>
										<td>
											<table id="specificationProductTable" class="table table-striped table-bordered">
											[#list specificationResultDto as ResultDto]
											[#list ResultDto.specification as specification]
											 <tr class="specification_${specification.id} hidden">
												<td>	
											<!--   <span id="Title_${specification.id}"> ${specification.name}:</span> -->
											<ul class="specificationSelect" id="Title_${specification.id}"> <li>${specification.name}</li></ul>
											  </td>
											  <td>
						                        <ul class="Title_${specification.id} Father_Item Item specificationSelect" id="Item_${specification.id}">
						                        [#list ResultDto.specificationValues as specificationValue]
													<li class="li_width">
													<label>
													<input type="checkbox" name="specificationValues" value="${specificationValue.id}_${specification.id}" data-value="${specificationValue.id}" data-val="${specificationValue.name}"/>${specificationValue.name}														
													</label>
													</li>
											    [/#list]
											    </ul>
											   </td>
												</tr>
													[/#list]
						                      [/#list]
											</table>
										</td>
									</tr>
									<tr>
									  <td> 填写价格，库存</td>
									  <td id="createTable"></td>
									</tr>
					              </table>
					          </div>
                          </div>
                        </div>
                 </div>
	         </div>
	         <div class="goods-info-group-inner">
	             <div class="info-group-title vbox">
					<div class="group-inner">商品信息</div>
				 </div>
				 <div class="info-group-cont vbox">
                        <div class="group-inner">
                          <div class="form-group">
                             <label class="col-md-2 control-label">商品名：<span style="color: red;"><em>*</em></span></label>
                              <div class="col-md-4" id="error_product_name">
					                <input type="text" id="product_name"  name="name" value=""  class="form-control"/>
					                <label class="control-label" for="product_name"></label>
					          </div>
                          </div>
                          <div id="unified">
                          <div class="form-group">
                             <label class="col-md-2 control-label">价格：<span style="color: red;"><em>*</em></span></label>
                              <div class="col-md-2" id="error_product_price">

								  <input type="text" id="product_price" name="price" class="form-control" onkeyup="value=value.replace(/[^\d.]/g,'')"/>
								   <label class="control-label" for="product_price"></label>
					          </div>
                          </div>
                          <!-- <div class="form-group">
                             <label class="col-md-2 control-label">市场价：</label>
                              <div class="col-md-2" id="error_product_price">
								 <input type="text" name="market_price" class="form-control" placeholder="市场价：￥99.99" onkeyup="value=value.replace(/[^\d.]/g,'')"/>
					          </div>
                          </div> -->
                          <div class="form-group">
                             <label class="col-md-2 control-label">商品库存：<span style="color: red;"><em>*</em></span></label>
                              <div class="col-md-2">
					                <input type="text" id="allStock"  name="stock" value="0" class="form-control" placeholder="比如填写100" onkeyup="value=value.replace(/[^\d]/g,'')"/>
					          </div>
                          </div>
                          </div>
                          <div class="form-group">
                             <label class="col-md-2 control-label">设置：<span style="color: red;"><em>*</em></span></label>
                              <div class="col-md-2">
                              <label>
									<input type="checkbox" name="isMarketable" value="true" checked="checked" />是否上架
									<input type="hidden" name="_isMarketable" value="false" />
							  </label>
							  <label>
									<input type="checkbox" name="isList" value="true" checked="checked" />是否列出
									<input type="hidden" name="_isList" value="false" />
							  </label>
                              </div>
                          </div>
                           <div class="form-group">
                             <label class="col-md-2 control-label">商品图：<span style="color: red;"><em>*</em></span></label>
                             
                             <div class="col-md-5">
                                 <ul class="js-picture-lists app-image-list">
					                <li><a href="javascript:;" onclick="addPicture(false);" class="add-goods js-add-picture show">+加图</a></li>
				                 </ul>
				                 <label id="image_error_msg" style="color:red;"></label>
					          </div>
                           </div>
                        </div>
                 </div>
	         </div>
	         <div class="goods-info-group-inner">
	             <div class="info-group-title vbox">
					<div class="group-inner">物流/其它</div>
				 </div>
				 <div class="info-group-cont vbox">
                        <div class="group-inner">
                        <div class="form-group">
                             <label class="col-md-2 control-label">运费设置：<span style="color: red;"><em>*</em></span></label>
                              <div class="col-md-4" id="error_delivery_fees">
                              <label>
									<input id="js-unified-postage" name="delivery_type" value="0" checked="" type="radio" onclick="changeDelivertyType();">
									统一邮费 
					               <div class="input-group" style="margin-bottom: 0px;vertical-align: middle;display: inline-block;">
									  <input type="text" id="delivery_fees" name="delivery_fees"  value="0.00" class="form-control" onkeyup="value=value.replace(/[^\d.]/g,'')"/>
									  <label class="delivery_fees_error_msg" style="color:red;"></label>
								   </div>
					          </label>
					          </div>
                          </div>
                          <div class="form-group">
                          <label class="col-md-2 control-label"></label>
                              <div class="col-md-6">
                              <label>
									<input id="js-unified-postage" name="delivery_type" value="1"  type="radio" onclick="changeDelivertyType();"/>
									运费模板
									<div  class="delivery-template" style="display: inline-block;vertical-align: middle;">
									   <select class="form-control" name="delivery_template_id" id="delivery_memo">
									   </select>
								   </div>
					               <div class="help-inline" style=" display: inline-block;padding-left: 5px;vertical-align: middle;">
					               <a class="js-refresh-delivery" href="javascript:;">刷新</a>
					               <span class="c-gray">|</span>
                                   <a class="new-window" href="${webctx}/delivery/add" target="_blank">新建</a>
					               </div>
					          </label>
					          <label class="delivery_template_error_msg" style="color:red;"></label>
					          </div>
                          </div>
                          
                          <div class="form-group" id="weight_memo" style="display: none">
	                          <div class="form-group">
	                                <label class="col-md-2 control-label"></label>
	                                <div class="col-md-6" style="color: #999999;">
	                                  <label> 当前运费模板，按物流重量（含包装）计费</label>
	                                </div>
	                              </div>
                          
                              <label class="col-md-2 control-label"></label>
                              <div class="col-md-10">
                              <label class="control-label">物流重量：<span style="color: red;"><em>*</em></span></label>
                                  <div class="input-group" id="unified_weight" style="margin-bottom: 0px;vertical-align: middle;display: inline-block;hidden">
									  <input type="text" id="delivery_weight" name="delivery_weight"  value="" class="form-control" onkeyup="value=value.replace(/[^\d.]/g,'')"/>
									  <label class="delivery_weight_error_msg" style="color:red;"></label>
								  </div>
								  
								  <div class="input-group" id="disunified_weight" style="margin-bottom: 0px;vertical-align: middle;display: inline-block;hidden">
									  <div id="createdWeight"></div>
								  </div>
								  
                              </div>
                           </div>
                        </div>
                  </div>
              </div>
	         
	     </div>
	   </div>	
	    <div class="panel-heading" style="background-color:#f8f8f8;border-bottom:5px solid #fff;height: 50px;text-align: center;">
	    <button type="button"  onclick="lastStepFirst();" class="btn btn-default">上一步</button>
      <button type="button"  onclick="nextStepThree();" class="btn  btn-primary">下一步</button>
   </div>
	   
	</div>

	<div id="js-step-3"  role="tabpanel" class="tab-pane">
     <div id="step-content-region" style="padding-top: 20px;">
		 <div class="app-sidebar-inner js-sidebar-region" style="width: 396px; z-index: 1;padding-top: 20px;">    
		   <script type="text/plain" id="editor" name="introduction"></script>
		 </div>		 
     </div>
     <div class="panel-heading" style="background-color:#f8f8f8;border-bottom:5px solid #fff;height: 50px;text-align: center;">
      <button type="button"  onclick="lastStepTwo();" class="btn btn-default">上一步</button>
       <button type="button" onclick="saveTaskForm();"  class="btn  btn-primary">上架</button>
   </div>
 </div>
	
</div>

<div class="col-sm-3">
	            <div class="wrapper wrapper-content project-manager">
	                <h4>帮助说明</h4>
	                <ol>
	                    <li>第一步：选择商品分类</li>
	                    <li>第二步：填写商品基本信息</li>
	                    <li>第二步：填写商品详细信息</li>
	                    <li>商品规格如何新建:操作路径：微商城，左侧导航，商品－规格－添加规格后：出现在商品基本信息《库存/规格》的多规格里</li>
	                </ol>
	            </div>
	</div>	
</div>
</form>
<script type="text/template" id="ul_li_tpl">
    <li data-file="{filePath}" data-fileUrl="{fileName}" style="display: inline-block;">
       <img alt="" src="{filePath}">
       <div class="image-title">{fileName}</div>
    </li>
</script>
<script type="text/template" id="select_memo">
    <option value="{id}">{name}</option>
</script>
<script type="text/template" id="no_select_memo">
    <option value="0">没有可用运费模板</option>
</script>
[/@layout]
<script>
Template.init("#menu-goods");
</script>
<script type="text/javascript">
//判断是不是运费模板
function changeDelivertyType(){
	var type = $("input[name='delivery_type']:checked").val();
	if(type=="0"){
		$("#weight_memo").hide();
	}else{
		var p1=$('#delivery_memo').children('option:selected').val();
		 $.post(obz.ctx+"/delivery/getDeliveryMemoName", {id:p1}, function(json) {
			 var dataList = json;
				if(dataList.length>0){
					var valuation_type=dataList[0].valuation_type;
					if(valuation_type=="2"){
						$("#weight_memo").show();	
					}else{
						$("#weight_memo").hide();
					}
				}
		 });
	}
}
$(document).ready(function() {
	selectMemo();
	
	$('#delivery_memo').change(function(){
		var p1=$(this).children('option:selected').val();//这就是selected的值
		 $.post(obz.ctx+"/delivery/getDeliveryMemoName", {id:p1}, function(json) {
			 var dataList = json;
				if(dataList.length>0){
					var valuation_type=dataList[0].valuation_type;
					if(valuation_type=="2"){
						$("#weight_memo").show();
						var type = $("input[name='is_unified_spec']:checked").val();
						if(type=="true"){
							$("#unified_weight").show();
							$("#disunified_weight").hide();
							}else{
						    $("#unified_weight").hide();
						    $("#disunified_weight").show();
							}
					}else{
						$("#weight_memo").hide();
					}
				}
		 });
		});
});
//刷新模板
$(function (){
	var s=$(".help-inline");	
	 s.on("click",".js-refresh-delivery",function(s){
		 $("#delivery_memo").empty();
		 selectMemo();
	});
});
//选择运费模板
function selectMemo(){
	 var params={};
		 $.post(obz.ctx+"/delivery/getDeliveryMemoName", params, function(json) {
			 var dataList = json;
				if(dataList.length>0){
					for(var i=0;i<dataList.length;i++){
						var _row = dataList[i];
						var optionHtml = obz.dataTemplate4obj($("#select_memo").html(), _row);	
						$("#delivery_memo").append(optionHtml);
					}
				}else{
					$("#delivery_memo").append($("#no_select_memo").html());
				}
		}); 
	}
var ue = UE.getEditor('editor',{
	toolbars: [
				["bold", "italic", "underline", "strikethrough", "forecolor", "backcolor", "justifyleft", "justifycenter", "justifyright", "|", "insertunorderedlist", "insertorderedlist", "blockquote",
				"simpleupload", "insertimage", "insertvideo", "link", "removeformat", "|", "rowspacingtop", "rowspacingbottom", "lineheight", "paragraph", "fontsize",
				"inserttable", "deletetable", "insertparagraphbeforetable", "insertrow", "deleterow", "insertcol", "deletecol", "mergecells", "mergeright", "mergedown", "splittocells", "splittorows", "splittocols"]
			],
			autoClearinitialContent: true,
			enableAutoSave: false,
			autoFloatEnabled: !0,
			wordCount: !1,
			elementPathEnabled: !1,
  		/* 	initialFrameWidth: 396, */
			 initialFrameHeight: 350, 
			focus: !1,
			pasteplain: !1
});
</script>
</body>
</html>